/**
 * @author jh.pei
 * @date 2024/10/23 10:25
 */
public class 两个链表的第一个公共结点 {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode p1 = pHead1;
        ListNode p2 = pHead2;
        if (p1 == null || p2 == null) {
            return null;
        }
        while (p1 !=null && p2 !=null) {
            if (p1 == p2) {
                return p1;
            }
            p1 = p1.next;
            p2 = p2.next;
        }
        if (p1  == null) {
            p1 = pHead2;
            while (p1 != null) {
                if (p2 == null) {
                    p2 = pHead1;
                }
                if (p1 == p2) {
                    return  p1;
                }
                p1 = p1.next;
                p2 = p2.next;
            }
            return null;
        }
        p2 = pHead1;
        while (p2 != null) {
            if (p1 == null) {
                p1 = pHead2;
                System.out.println("p122:"+p1.val);
            }
            if (p1 == p2) {
                return  p1;
            }
            System.out.println("p1:"+p1.val);
            System.out.println("p2:"+p2.val);
            p1 = p1.next;
            p2 = p2.next;
        }
        return null;
    }

    public ListNode FindFirstCommonNode2(ListNode pHead1, ListNode pHead2) {
       ListNode p1 = pHead1;
       ListNode p2 = pHead2;
       while (p1 != p2) {
           p1 = p1 == null ? pHead2 : p1.next;
           p2 = p2 == null ? pHead1 : p2.next;
       }
       return p1;
    }
}
